/********************************************************************************
 * Copyright(c) 2020-2025 BST All rights reserved.
 * - Filename
 * - Author
 * - Version V1.0.0
 * - Date    2024/09/9
 * - Brief
 * - FunctionList:
 ******************************************************************************
 * History:
 *
 *
 *
 ******************************************************************************
 */

#include "DetectInfoReciver.hpp"

#include <fstream>
#include <iostream>

#include "ConfigSingleton.hpp"
#include "Logger.hpp"
#include "google/protobuf/util/json_util.h"
#include "hv/base64.h"

using google::protobuf::util::JsonOptions;
using google::protobuf::util::MessageToJsonString;

DetectInfoReciver::DetectInfoReciver(void *context) {
  _context = (vzmq::VzmqContext *)context;
};
DetectInfoReciver::~DetectInfoReciver(){};
void DetectInfoReciver::start(const std::string &ip, DetectionCallback icb) {
  if (ip != "") _ip = ip;
  std::string REPLAY_IMAGE_FRAME_CHANNAL_SUB = "tcp://" + _ip + ":40400";
  _subscriber = _context->createSubscribler<DetectionFrame>(
      REPLAY_IMAGE_FRAME_CHANNAL_SUB,
      [&](const std::shared_ptr<DetectionFrame> &frame) {
        std::string jsonString;
        JsonOptions options;
        options.add_whitespace = true;
        options.always_print_primitive_fields = true;
        frame->mutable_image()->set_data("");
        if (MessageToJsonString(*frame, &jsonString, options) !=
            google::protobuf::util::Status::OK) {
          std::cerr << "Failed to convert to JSON." << std::endl;
          return;
        }

        std::string fileName(ConfigSingleton::get().getImagePath());
        fileName.append(frame->image().image_name());
        fileName.append(".json");
        std::ofstream jsonFile(fileName);
        if (!jsonFile.is_open()) {
          std::cerr << "Failed to open file." << std::endl;
          return;
        }
        jsonFile << jsonString;
        jsonFile.close();
        LOGI("Write file:%s", fileName.c_str());
        if (icb != nullptr) {
          icb(std::move(frame));
        }
      });
}
void DetectInfoReciver::stop() {}
bool DetectInfoReciver::writeJpegFile(
    const std::string &filename, const std::vector<unsigned char> &buffer) {
  std::ofstream outFile(filename, std::ios::binary | std::ios::trunc);

  if (!outFile.is_open()) {
    return false;
  }
  outFile.write(reinterpret_cast<const char *>(buffer.data()), buffer.size());
  return outFile.good();
}